package com.rcadmin.busi.web.service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Component;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.rcadmin.busi.web.dao.BlockDao;
import com.rcadmin.busi.web.ddl.WebBlock;
import com.rcadmin.busi.web.ddl.WebTemplateGroupkey;
import com.rcadmin.busi.web.dto.WebBlockDto;
import com.rcadmin.core.jpa.BaseDao;
import com.rcadmin.core.jpa.util.PageBean;

/**
 * 内容服务类
 * 
 * @author tanson lam
 * @create 2016年10月24日
 */
@Component
public class BlockService {
	@Resource
	private BaseDao baseDao;
	@Resource
	private BlockDao blockDao;
	@Resource
	private GroupKeyService groupKeyService;

	/**
	 * 查找单个内容信息
	 * 
	 * @param userId
	 * @param blockId
	 * @return
	 */
	public WebBlock findOne(Integer userId, Integer blockId) {
		return blockDao.findOne(userId, blockId);
	}

	public PageBean<WebBlockDto> pageQuery(String condition, String orderBy,
			Integer pageSize, Integer page) {
		PageBean<WebBlock> entityPageBean = baseDao.pageQuery(condition,
				orderBy, pageSize, page, WebBlock.class);
		List<WebBlockDto> dtoList = Lists.newArrayList();
		final List<Integer> groupKeyIdList = Lists.transform(
				entityPageBean.getResult(), new Function<WebBlock, Integer>() {
					@Override
					public Integer apply(WebBlock model) {
						if (model == null)
							return null;
						return model.getGroupKeyId();
					}
				});

		Map<Integer, WebTemplateGroupkey> templatePackMap = groupKeyService
				.findByGroupKeyIds(groupKeyIdList);
		for (WebBlock model : entityPageBean.getResult()) {
			WebBlockDto dto = new WebBlockDto();
			try {
				BeanUtils.copyProperties(dto, model);
				if (model.getGroupKeyId() != null
						&& templatePackMap.get(model.getGroupKeyId()) != null) {
					dto.setGroupKeyName(templatePackMap.get(
							model.getGroupKeyId()).getName());
					dto.setGroupKey(templatePackMap.get(model.getGroupKeyId())
							.getGroupKey());
				}
				dtoList.add(dto);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}

		return PageBean.copy2DtoPageBean(entityPageBean, dtoList);
	}
}
